

package commandz.var;


/**
 *  A floating point specialized implementation of the Variable interface.
 *
 *  This class is applicable when a Variable for real numbers is needed.
 */
public class VariableReal implements Variable
{
    private final String VARIABLE_NAME = "real";

    protected float value;


    /**
     *  Initializes a new instance of the VariableReal class
     *  with the default value 0.
     */
    public VariableReal()
    {
        this.value = 0;
    }


    /**
     *  Initializes a new instance of the VariableReal class
     *  with the given value.
     *
     *  @param value A real value to use for initialization.
     */
    public VariableReal(final float value)
    {
        this.value = value;
    }


    /**
     *  Assigns the value of this VariableReal to the given one.
     *
     *  @param value A real value to use.
     */
    public void setValue(final float value)
    {
        this.value = value;
    }


    /**
     *  Returns the value used by this VariableReal.
     *
     *  @return A floating point value.
     */
    public float getValue()
    {
        return this.value;
    }


    /**
     *  Returns the name of the type of this Variable.
     *
     *  @return A String containing the type-name of this Variable.
     */
    public String getTypeName()
    {
        return this.VARIABLE_NAME;
    }


    /**
     *  Parses the given string into the value of this Variable.
     *
     *  @param str A String holding the representation of a real value.
     *
     *  @return true on success, false on error.
     */
    public boolean parse(String str)
    {
        try // to parse...
        {
            this.value = Float.parseFloat(str);
        }
        catch (NumberFormatException e)
        {
            return false;
        }

        return true;
    }


    /**
     *  Formats the value of this Variable into a readable String.
     *
     *  @return A textual representation of a real value.
     */
    public String format()
    {
        return String.format("%.2f", this.value);
    }
}
